<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div, ul, li {
            margin: 0;
            padding: 0
        }

        li {
            float: left;
            width: 100px;
            height: 24px;
            line-height: 24px;
            list-style: none;
            border: solid 1px;
            text-align: center;
        }

        #cart {
            width: 700px;
            text-align: center;
        }

        .num input {
            width: 30px;
            text-align: center;
        }

        ul {
            background-color: cornflowerblue;

        }

        /*ul:nth-child(0) {*/
        /*background-color: aqua;*/
        /*}*/

        .num {
            width: 150px;
        }

        #total {
            clear: both;
            text-align: right;
            padding-right: 50px;
            padding-top: 5px;
        }

        #total span {
            color: red
        }

        .no {
            width: 660px;
            height: 24px;
            border: 1px solid #000;
            float: left;
        }
    </style>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script>
        window.onload = function () {
            const {createApp, ref, watch, watchEffect} = Vue

            createApp({
                setup() {
                    let products = [
                        {name: "电脑", price: 10000},
                        {name: "u盘", price: 23},
                        {name: "充电器", price: 45},
                        {name: "鼠标", price: 65}];

                    //添加
                    const cartProducts = ref([])
                    const insert = () => {
                        let index = Math.floor(Math.random() * 4);
                        let product = cartProducts.value.find(item => item.name === products[index].name)
                        if (product) {
                            product.count++
                        } else {
                            cartProducts.value.push({...products[index], count: 1})
                        }
                    }

                    //增加
                    const add = (product) => {
                        product.count++
                    }

                    //减少
                    const sub = (product) => {
                        if (product.count > 1) {
                            product.count--
                        } else {
                            cartProducts.value = cartProducts.value.filter(item => item.name !== product.name)
                        }
                    }

                    //删除
                    const del = (index) => {
                        cartProducts.value.splice(index, 1)
                    }

                    //watch监听数组，控制数量不能为零。
                    watch(() => [cartProducts.value.map(product => product.count)], (newValue, oldValue) => {
                        // console.log(newValue, "--", oldValue)
                        newValue.forEach(function (val, index) {
                            if (val == 0) {
                                alert('数量不能少于1');
                                cartProducts.value[index].count = oldValue[index]
                            }
                        })
                    }, {deep: true})

                    //全选
                    const all = ref(false)
                    const checkedNames = ref([])
                    const checkAll = () => {
                        //console.log(checkedNames.value)
                        if (!all.value) {
                            //遍历cartProduct，获得所有 name 插入checkedNames中
                            checkedNames.value = cartProducts.value.map(product => product.name)
                        } else {
                            //checkedNames.value.splice(0, checkedNames.value.length)
                            checkedNames.value.length = 0
                        }
                    }

                    //watch监听数组，计算总价
                    const totalFee = ref(0)
                    // watch(cartProducts, (newValue, oldValue) => {
                    //     console.log(newValue, "--", oldValue)
                    //     let sum = 0;
                    //     cartProducts.value.forEach(item => {
                    //         sum += item.price * item.count
                    //     })
                    //     totalFee.value = sum
                    // }, {deep: true})
                    watch([checkedNames,cartProducts], (newValue, oldValue) => {
                        console.log(newValue, "--", oldValue)
                        let sum = 0;
                        //1、双重for循环
                        // cartProducts.value.forEach(item => {
                        //     for(let name of checkedNames.value){
                        //         if(name === item.name){
                        //             sum += item.price * item.count
                        //         }
                        //     }
                        // })

                        //2、cartProducts转换成map，然后循环checkedNames
                        // const map = new Map(Array.from(cartProducts.value, item => [item.name, item]))
                        // checkedNames.value.forEach(item=>{
                        //     sum += map.get(item).price * map.get(item).count
                        // })

                        //3、交集
                        let intersect = [...cartProducts.value].filter(x => checkedNames.value.includes(x.name)); // {2, 3}
                        intersect.forEach(item => {
                            sum += item.price * item.count
                        })
                        totalFee.value = sum

                        //控制全选checkbox
                        //取消全选
                        if(checkedNames.value.length < cartProducts.value.length){
                            all.value = false;
                        }
                        //显示全选
                        if(checkedNames.value.length === cartProducts.value.length){
                            all.value = true;
                        }

                    }, {deep: true})

                    return {all, totalFee, checkedNames, cartProducts, checkAll, add, insert, del, sub}
                }
            }).mount('#cart')
        }
    </script>

</head>
<body>
<div id="cart">
    <ul>
        <li><input v-model="all" type="checkbox" @click="checkAll()">全选</li>
        <li>产品名称</li>
        <li>价格</li>
        <li class="num">数量</li>
        <li>合计</li>
        <li>操作</li>
    </ul>
    <!--view-->
    <ul v-for="(product,index) in cartProducts" :key="product.name">
        <li><input v-model="checkedNames" :value="product.name" type="checkbox"></li>
        <li>{{product.name}}</li>
        <li>{{product.price}}</li>
        <li class="num">
            <input type="button" value="-" @click="sub(product)">
            <input v-model.lazy="product.count" type="text">
            <input type="button" value="+" @click="add(product)">
        </li>
        <li>{{product.price * product.count}}</li>
        <li><span @click="del(index)">删除</span></li>
    </ul>
    <div class="no" v-if="cartProducts.length === 0">暂无商品</div>
    <div id="total" v-else>总价:<span>{{totalFee}}</span></div>
    <input name="add" type="button" value="添加" @click="insert()">
</div>
</body>
</html>
